﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.Bill.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DzInfo.FormPlugIn.XJCX
{
    [Description("XJCX销售出库单自动填写在库序列号"), HotUpdate]
    public class AutoSN : AbstractBillPlugIn
    {
        public override void AfterEntryBarItemClick(AfterBarItemClickEventArgs e)
        {
            base.AfterEntryBarItemClick(e);
            if (e.BarItemKey.Equals("NUHN_tbButton"))
            {
                DynamicObjectCollection Entrys = this.View.Model.DataObject["SAL_OUTSTOCKENTRY"] as DynamicObjectCollection;
                DynamicObject snojb = null;
                //循环单据体数据包获取序列号数量、物料id、批号id
                foreach (var Entry in Entrys)
                {
                    int Seq = Convert.ToInt32(Entry["Seq"]);
                    int SNQty = Convert.ToInt32(Entry["SNQty"]);
                    string stockId = Entry["StockID_id"].ToString();
                    string Materialid;
                    //string Lot_TEXT;
                    if (!Entry["MATERIALID_id"].IsNullOrEmptyOrWhiteSpace())
                    {
                        Materialid = Entry["MATERIALID_id"].ToString();
                        //Lot_TEXT = Entry["LOT_TEXT"].ToString();
                    }
                    else
                    {
                        this.View.ShowErrMessage("请检查是否录入了物料编码,行号：" + Entry["Seq"]);
                        break;
                    }
                    //判断序列号数量，大于0才给序列号子单据体赋值
                    if (SNQty > 0)
                    {
                        //赋值序列号前，默认触发行点击事件，让系统创建子单据体序列号对应数量行
                        ((IDynamicFormViewService)this.View).EntityRowClick("FEntity", Seq - 1);
                        //根据物料id、批号id、仓库查询在库状态（stockstatus=1）的序列号,根据序列号数量查询前N条数据
                        string sql = "select top " + SNQty + " a.FSERIALID,a.FSERIALID,FNUMBER,FSTOCKSTATUS,c.FLOT from T_BD_SERIALMASTER a " +
                            "left join T_BD_SERIALMASTERORG b on a.FSERIALID=b.FSERIALID " +
                            "left join T_BD_SERIALMASTEROTHER c on c.FSERIALID=a.FSERIALID " +
                            "where FMATERIALID='" + Materialid + "' " +
                            "and FSTOCKSTATUS=1 and (F_PHYE_COMBO=1 OR F_PHYE_COMBO='' ) and FSTOCKID = '" + stockId + "'";
                        DynamicObjectCollection dts = DBUtils.ExecuteDynamicObject(this.Context, sql);
                        EntryEntity entryRow = this.View.BusinessInfo.GetEntryEntity("FSerialSubEntity");
                        DynamicObjectCollection subEntryRows = entryRow.DynamicProperty.GetValue(Entry) as DynamicObjectCollection;
                        int i = 0;
                        //判断查询的序列号数量是否和单据序列号行数一致，不一致不自动填充，人工判断选择
                        if (dts.Count == subEntryRows.Count)
                        {
                            foreach (var subEntry in subEntryRows)
                            {
                                if (subEntry["SerialNo"].IsNullOrEmptyOrWhiteSpace())
                                {
                                    subEntry["SerialNo"] = dts[i]["FNUMBER"];
                                    //对本单已赋值使用的序列号更新标识，避免本单据其他相同批号物料行再次使用本序列号
                                    var sqlx = string.Format("update T_BD_SERIALMASTERORG set F_PHYE_COMBO =2 where FSERIALID='" + dts[i]["FSERIALID"] + "' ");
                                    DBUtils.Execute(this.Context, sqlx);
                                }
                                i++;
                            }
                        }
                    }
                }
                //序列号赋值循环完后更新辅助标识为1，以避免单据删除后，下次再下推无法再次匹配
                foreach (var Entry in Entrys)
                {
                    EntryEntity entryRow = this.View.BusinessInfo.GetEntryEntity("FSerialSubEntity");
                    DynamicObjectCollection subEntryRows = entryRow.DynamicProperty.GetValue(Entry) as DynamicObjectCollection;
                    foreach (var subEntry in subEntryRows)
                    {
                        var sqlz = string.Format("/*dialect*/update T_BD_SERIALMASTERORG set F_PHYE_COMBO =1 " +
                            "from T_BD_SERIALMASTERORG a left join T_BD_SERIALMASTER b on a.FSERIALID = b.FSERIALID " +
                            "where FNUMBER = '" + subEntry["SerialNo"].ToString() + "'");
                        DBUtils.Execute(this.Context, sqlz);
                    }
                }
                DBServiceHelper.LoadReferenceObject(this.Context, Entrys.ToArray(), Entrys.FirstOrDefault().DynamicObjectType, false);
                this.View.UpdateView("FSerialSubEntity");
            }
        }
    }
}
